package com.waa.gulimall.cart.interceptor;

import com.waa.gulimall.cart.to.UserInfoTo;
import com.waa.gulimall.common.constant.AuthServerConstant;
import com.waa.gulimall.common.constant.CartConstant;
import com.waa.gulimall.common.vo.MemberRespVo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 在执行目标方法之前，判断用户的登陆状态，并封装传递给Controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {
public static ThreadLocal<UserInfoTo> threadLocal =  new ThreadLocal<UserInfoTo>();
    /**
     *目标方法执行前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final UserInfoTo userInfoTo = new UserInfoTo();
        final HttpSession session = request.getSession();
        final MemberRespVo  memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
          if (null!= memberRespVo) {
              //用户登录
              userInfoTo.setUserId(memberRespVo.getId());
          }
        final Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            final String cookieName = cookie.getName();
            if (cookieName.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                userInfoTo.setUserKey(cookie.getValue());
                userInfoTo.setTempUser(true);
            }
        }
        //目标方法执行前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //业务执行完之后给浏览器存一个cookie
        if (!threadLocal.get().isTempUser()){//判断是否有临时用户了
        final Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
         cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);//设置cookie的过期时间
        cookie.setDomain("changgou.com");
        response.addCookie(cookie);
        }
    }
}
